/*
 *  Gurr - A multiprotocol chat client for Android
 *  Copyright (C) 2011 Malte Aschermann, Wilfried Ramaker
 *  
 *  This file is part of Gurr.
 *  
 *  Gurr is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *  
 *  Gurr is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *  
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with Gurr.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.masc.gurr.view.activities;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.masc.gurr.Controller;
import com.masc.gurr.R;
import com.masc.gurr.model.Account;
import com.masc.gurr.model.Contact;
import com.masc.gurr.model.ProtocolType;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.EditText;

public class AccountActivity extends Activity {
	private Button btLogin;
	private Button btLogOut;
	private Button btAddAccount;
	
	public AccountActivity() {
		// Register Activity
        Controller.getInstance().setAccountActivity(this);
	}
	
	
    @Override
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.account);
        
        /* read accounts from internal xml storage */
        Controller.getInstance().readStoredAccounts();
        
        // load xml contact list, if exists, for offline browsing
        Controller.getInstance().loadContactList();

        Controller.getInstance().readHistory();

        btLogin = (Button) findViewById(R.id.btLogin);
        btLogOut = (Button) findViewById(R.id.btLogOff);
        btAddAccount = (Button) findViewById(R.id.btAddAccount);
        final Button btExit = (Button) findViewById(R.id.btExit);
        
        fillAccountSpinner();
        
        Spinner spAccount = (Spinner) findViewById(R.id.spAccount);

        spAccount.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> arg0, View v,
					int pos, long id) {
		        Spinner spAccount = (Spinner) findViewById(R.id.spAccount);
		        String uid="";
		        String item = (String) spAccount.getAdapter().getItem(pos);
		        
		        /* get uin */
		        if (item.contains("(") && item.contains(")")) {
		        	uid = item.substring(item.indexOf('(')+1, item.indexOf(')'));
		        } else {
		        	uid = item;
		        }
		        
		        Controller.getInstance().getAccountMap().selectAccount(
		        		uid
		        		);
		        		        
		        /* call contactactivity onContentChanged to update contact list */
				if (Controller.getInstance().getContactsActivity() != null) {
					Controller.getInstance().loadContactList();
					Controller.getInstance().readHistory();
					
					Controller.getInstance().getContactsActivity().rebuild();					
				}
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				
			}
		});
        
        btLogin.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

            	Controller.getInstance().connectICQ(
            			Controller.getInstance().getMyAccount().getUin(),
            			Controller.getInstance().getMyAccount().getPass()
            			);
            	Toast.makeText(getApplicationContext(), "connecting "
            			+ Controller.getInstance().getMyAccount().getUin(),
                        Toast.LENGTH_SHORT).show();
            }
        });
        
        btLogOut.setOnClickListener(new View.OnClickListener() {	
			public void onClick(View arg0) {
				// ICQ-Disconnect...
				// save History..
				Toast.makeText(getApplicationContext(), "disconnecting", Toast.LENGTH_SHORT).show();
				Controller.getInstance().disconnectICQ();
				if (Controller.getInstance().getContactsActivity() != null) {
					Controller.getInstance().loadContactList();
					Controller.getInstance().getContactsActivity().rebuild();
				}
			}
		});
        
        btAddAccount.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				addAccount();
			}
		});
        
		btExit.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});
    }

    private void fillAccountSpinner() {
    	/* fill spinner w/ account uins */
        Spinner spAccount = (Spinner) findViewById(R.id.spAccount);
        Iterator<Account> ita = Controller.getInstance().getAccountMap().getAllAccounts();
        List<String> lstA = new ArrayList<String>();
        while (ita.hasNext()) {
			Account a = (Account) ita.next();
			if (! a.getAlias().equals(a.getUin()))
				lstA.add(a.getAlias() + " (" + a.getUin() + ")");
			else
				lstA.add(a.getUin());
        }
        
        ArrayAdapter adapter = new ArrayAdapter(
				this,
				android.R.layout.simple_dropdown_item_1line, 
				lstA.toArray());
        spAccount.setAdapter(adapter);   
	}

	private void addAccount() {
    	LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
    	final View layout = inflater.inflate(R.layout.add_account_dialog,
    	                               (ViewGroup) findViewById(R.id.user_pass_root));
		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		
		alert.setTitle("Add ICQ Account");
		alert.setPositiveButton("Add Account",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,
							int whichButton) {
						
						EditText etUin = (EditText) layout.findViewById(R.id.etUin);
						EditText etAlias = (EditText) layout.findViewById(R.id.etAlias);
						EditText etPass = (EditText) layout.findViewById(R.id.etPass);
						
						
						/* add new account */
						if (etAlias.getText().toString().equals(""))
							Controller.getInstance().getAccountMap()
								.addAccount(
										ProtocolType.ICQ, etUin.getText().toString(), 
										etPass.getText().toString()
										);
						else
							Controller.getInstance().getAccountMap()
							.addAccount(
									ProtocolType.ICQ, etUin.getText().toString(), 
									etPass.getText().toString(),
									etAlias.getText().toString()
									);
						Controller.getInstance().getAccountActivity().onContentChanged();
		            	fillAccountSpinner();
		            	
						/* save account login */
		            	Controller.getInstance().getAccountMap().selectAccount(etUin.getText().toString());
		            	Controller.getInstance().writeAccounts();
					}
		});
		alert.setView(layout);
		
		alert.setNegativeButton("Abort",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
					}
				});
		alert.show();
    }
    
	public Button getBtIcqLogin() {
		return btLogin;
	}

	public void setBtIcqLogin(Button btIcqLogin) {
		this.btLogin = btIcqLogin;
	}

	public Button getBtIcqLogOut() {
		return btLogOut;
	}

	public void setBtIcqLogOut(Button btIcqLogOut) {
		this.btLogOut = btIcqLogOut;
	}
}